var app = getApp();
const orginalPrice = 0; //由于0.00在赋值时是0，用toFixed()取余
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectTab: true,
    selectBook: true,
    selectThing: false,

    carts: [], // 购物车列表
    hasList: false, // 列表是否有数据
    totalPrice: orginalPrice.toFixed(2), // 总价，初始为0
    selectAllStatus: false, // 全选状态，默认全选
    bookId: '',
    isMyCartShow: false,
    studentId: '',
    myCartBookLength: '5',
    bookPrice: 0,

    thingId: '',
    thingCarts: [], // 物品列表
    isThingCartShow: false,
    myCartThingLength: '5',
    thingPrice: 0,
    num:1,
    parameter: [{ "shopcart_id": 1, "goods_num": 2,"coupon_record_id":0}],//提交的json数组
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    this.getCartList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 动态设置导航条标题
    wx.setNavigationBarTitle({
      title: '购物车'
    });
    wx.showNavigationBarLoading(); //在标题栏中显示加载图标
    setTimeout(function () {
      wx.stopPullDownRefresh(); //停止加载
      wx.hideNavigationBarLoading(); //隐藏加载icon
    }, 2000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
      // this.getCartList()
  },

  //获取购物车列表
  getCartList() {
    var that = this;
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 1000,
    })

    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=Shopcart&a=getShopcartList',
      data:
      {
        token: app.globalData.token,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        for(var i=0;i<res.data.data.list.length;i++){
          res.data.data.list[i].img = app.globalData.imgUrl + "" + res.data.data.list[i].img;
        }
        that.setData({
          carts: res.data.data.list
        })
        if(that.data.carts.length==0){
          that.setData({
            hasList:false
          })
        }
        that.getAddressList();
      }, fail: function () {

      }
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  //事件处理函数
  /*点击减号*/
  bindMinus: function (e) {
    const index = e.currentTarget.dataset.index;    // 获取data- 传进来的index
    let carts = this.data.carts; // 获取购物车列表
    var num=carts[index].goods_num;
    if (num > 1) {
      num--;
    }
    console.log(num)
    this.changeCartNum(index, carts[index].id, num);
  },
  /*点击加号*/
  bindPlus: function (e) {
    const index = e.currentTarget.dataset.index;    // 获取data- 传进来的index
    let carts = this.data.carts; // 获取购物车列表
    this.data.num++;
    console.log(this.data.num)
    this.changeCartNum(index, carts[index].id,this.data.num);
  },

//修改购物车数量
  changeCartNum(index,id,num){
    var that=this;
    let carts = that.data.carts; // 获取购物车列表
    wx.request({
      url: app.globalData.api + '/index.php/wap/Shopcart/changeNum',
      data:
      {
        token: app.globalData.token,
        id: id,
        num:num
      },
      headers: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        if (res.data.code == 1) {
          carts[index].goods_num = num;              // 改变数量
          that.setData({
            carts: carts
          });
          // console.log(that.data.carts)
        }
        that.getTotalPrice();
      }, fail: function () {

      }
    });
  },
  /*输入框事件*/
  bindManual: function (e) {
    var num = e.detail.value;
    var minusStatus = num > 1 ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus
    })
  },

  //计量总价
  getTotalPrice() {
    let carts = this.data.carts; // 获取购物车列表
    let thingPrice = parseFloat(this.data.thingPrice);
    let bookPrice = parseFloat(this.data.bookPrice);
    let total = 0.00;
    for (let i = 0; i < carts.length; i++) { // 循环列表得到每个数据
      if (carts[i].selected) { // 判断选中才会计算价格

        total += parseFloat(carts[i].price * carts[i].goods_num); // 所有价格加起来
      }
    }
    this.setData({
      bookPrice: total.toFixed(2)
    })
    total += thingPrice;
    this.setData({ // 最后赋值到data中渲染到页面
      carts: carts,
      totalPrice: total.toFixed(2) //保留小数后面2两位
    });
  },
  //选择事件
  selectList(e) {
    let that = this;
    const index = e.currentTarget.dataset.index;    // 获取data- 传进来的index
    // console.log(index);

    let selectAllStatus = that.data.selectAllStatus; //是否已经全选
    let str = true;  //用str与每一项进行状态判断
    let carts = that.data.carts;                    // 获取购物车列表
    const selected = carts[index].selected;         // 获取当前商品的选中状态
    carts[index].selected = !selected;              // 改变状态
    that.setData({
      carts: carts
    });
    console.log(that.data.carts)
    that.getTotalPrice();                           // 重新获取总价
    for (var i = 0; i < carts.length; i++) {
      str = str && carts[i].selected;           //用str与每一项进行状态判断
    }

    if (str === true) {
      that.setData({
        selectAllStatus: true
      })
    } else {
      that.setData({
        selectAllStatus: false
      })
    }
  },
  //全选事件
  selectAll(e) {
    var that = this;
    let selectAllStatus = that.data.selectAllStatus;    // 是否全选状态
    let carts = that.data.carts;
    let thingCarts = that.data.thingCarts;
    var selectThing = that.data.selectThing;
    var selectBook = that.data.selectBook;
      selectAllStatus = !selectAllStatus;
      for (let i = 0; i < carts.length; i++) {
        carts[i].selected = selectAllStatus;            // 改变所有商品状态
      }
      that.setData({
        selectAllStatus: selectAllStatus,
        carts: carts
      });
      that.getTotalPrice();                               // 重新获取总价
      if (carts.length === 0) { //当没有物品时，不能再点“全选”
        wx.showModal({
          title: '提示',
          content: '购物车空空如也~',
          success: function (res) {   //模糊层成功出来后
            if (res.confirm) {
              console.log('用户点击确定')
              that.setData({
                selectAllStatus: false
              })
            } else {
              console.log('用户点击取消')
              that.setData({
                selectAllStatus: false
              })
            }
          },
        })
      }
  },

  //删除商品
  deleteList(e) {
    const index = e.currentTarget.dataset.index;
    var selectAllStatus = this.data.selectAllStatus;
    let carts = this.data.carts;
    let totalPrice = this.data.totalPrice;
    wx.showModal({
      title: '提示',
      content: '将此产品移除购物车？',
      success: res => {
        if (res.confirm) {
          this.del(index);
          console.log('用户点击确定')
          
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },



//从购物车移除
  del(index) {
    var that = this;
    let carts = this.data.carts;
    console.log(carts)
    
    wx.request({
      url: app.globalData.api + '/app.php?c=Shopcart&a=del',
      data:
      {
        token: app.globalData.token,
        goods_id: carts[index].goods_id
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        if(res.data.code==0){
          carts.splice(index, 1);              // 删除购物车列表里这个商品
          if (carts.length == 0) {                 // 如果购物车为空
            that.setData({
              hasList: false,             // 修改标识为false，显示购物车为空页面
              selectAllStatus: false,
              totalPrice: orginalPrice.toFixed(2),              //此时价格为0
              carts:carts
            });
          } else {                              // 如果不为空
            that.getTotalPrice();           // 重新计算总价格
          }
        }    
      }, fail: function () {

      }
    });
  },

  //选择事件
  selectListThing(e) {
    let that = this;
    const index = e.currentTarget.dataset.index;    // 获取data- 传进来的index
    console.log(index);

    let selectAllStatus = that.data.selectAllStatus; //是否已经全选
    let str = true;  //用str与每一项进行状态判断
    let thingCarts = that.data.thingCarts;                    // 获取购物车列表
    const selected = thingCarts[index].selected;         // 获取当前商品的选中状态
    thingCarts[index].selected = !selected;              // 改变状态
    that.setData({
      thingCarts: thingCarts
    });
    that.getTotalPriceThing();                           // 重新获取总价
    for (var i = 0; i < thingCarts.length; i++) {
      str = str && thingCarts[i].selected;           //用str与每一项进行状态判断
    }
    console.log(str);
    if (str === true) {
      that.setData({
        selectAllStatus: true
      })
    } else {
      that.setData({
        selectAllStatus: false
      })
    }
  },


  chooseBookCart() {
    var that = this;
    var selectBook = that.data.selectBook;
    var selectThing = that.data.selectThing;
    let selectAllStatus = that.data.selectAllStatus; //是否已经全选
    let str = true;  //用str与每一项进行状态判断
    let carts = that.data.carts;
    for (var i = 0; i < carts.length; i++) {
      str = str && carts[i].selected;           //用str与每一项进行状态判断
    }
    console.log(str);
    that.setData({
      selectBook: true,
      selectThing: false,
    })

  },
  chooseThingCart() {
    var that = this;
    var selectThing = that.data.selectThing;
    var selectBook = that.data.selectBook;
    var selectAllStatus = that.data.selectAllStatus;

    that.setData({
      selectBook: false,
      selectThing: true,

    })

    // 此时data中的数据改变，但是此时的属性值还未改变

    that.getThingCartList()

  },
  toBuy() {
    if (this.data.isDefaultAddress){
      var bookCarts = this.data.carts;
      var bookCart = [];
      bookCarts.forEach(item => {
        if (item.selected) {
          bookCart.push(item);
        }
      })
      console.log(bookCart)
      this.setData({
        goodslist: this.data.parameter
      })
      this.orderByShopcart();
    }else{
        wx.showToast({
          title: '请选择收获地址',
          icon:'none'
        })

        wx.navigateTo({
          url: '/pages/mine/setting-addresslist',
        })
    }
    
  },

  

  //确认订单-购物车
  orderByShopcart() {
    var that = this;
   
    if(that.data.addressList.id==undefined){
        wx.showToast({
          title: '请先添加地址',
          icon:'none'
        })
    }else{
      console.log("addressid=" + that.data.addressList.id);
      console.log(that.data.goodslist)
      wx.request({
        url: app.globalData.api + '/app.php?c=Order&a=orderByShopcart',
        data:
        {
          token: app.globalData.token,
          goodslist: that.data.goodslist,
          address_id: '' + that.data.addressList.id,
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded",
          'platform': '' + app.globalData.platform,
          'version': '' + app.globalData.version,
        },
        method: 'POST',
        dataType: 'json',
        success: function (res) {
          console.log(res);
          if (res.data.code == 0) {
            that.getPayForm(res.data.data.order_id);
          } else {
            wx.showToast({
              title: '请求异常',
              icon:'none'
            })
          }

        }, fail: function () {

        }
      });
    }
    
  },

  //获取支付表单
  getPayForm(order_id) {
    var that = this;
    wx.request({
      url: app.globalData.api + '/index.php/wap/Order/getPayForm',
      data:
      {
        token: app.globalData.token,
        order_id: order_id,
        pay_method: '' + + app.globalData.payfrom,
      },
      headers: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        if (res.data.code == 1) {
          wx.showToast({
            title: '' + res.data.msg,
            icon: 'success',
            duration: 2000
          })
          // "{"appid":"wx48126316bdbec25b","noncestr":"lk8qhri54a7stxryu88e4n5tuhgc0f7f","package":"Sign = WXPay","partnerid":"1498191702","prepayid":"wx23131631764983da394a941c1058073000","sign_type":"HMAC - SHA256","timestamp":1590210991,"sign":"F9B89B33AC715AABE0C69AC825E1104BA283335731A01C1C7200C13420E65FFF"}"
          // var tempJson = JSON.parse(res.data.data.pay_parameters)
          // console.log(tempJson)
          // console.log(tempJson.appid)
          // var packages = "prepay_id=" + tempJson.prepayid
          // console.log(packages)
          // wx.requestPayment(
          //   {
          //     'timeStamp': '' + tempJson.timestamp,
          //     'nonceStr': '' + tempJson.noncestr,
          //     'package': "" + packages,
          //     'signType': 'MD5',
          //     'paySign': '' + tempJson.sign,
          //     'success': function (res) {
          //       console.log(res)
          //     },
          //     'fail': function (res) {
          //       console.log(res)
          //     },
          //     'complete': function (res) {
          //       console.log(res)
          //     }
          //   })
        } else {
          wx.showToast({
            title: '' + res.data.msg,
            icon: 'none',
            duration: 1000
          })
        }

      }, fail: function () {

      }
    });
  },

  //获取收货地址列表
  getAddressList() {
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=ConsigneeAddress&a=getAddressList',
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      data: {
        'token': '' + app.globalData.token
      },
      success: (res) => {
        console.log(res)
        if (res.data.data.list.length > 0) {
          for (var i = 0; i < res.data.data.list.length; i++) {
            if (res.data.data.list[i].is_default == 'Y') {
              that.setData({
                addressList: res.data.data.list[i],
                isDefaultAddress: true
              })
            }
          }
        } else {
          that.setData({
            isDefaultAddress: false
          })
        }
      },
    });
  },
})